package com.dataaccess.dataaccess.common.base;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.dataaccess.dataaccess.common.utils.appkit.ConfigKit;
import com.dataaccess.dataaccess.common.utils.appkit.FirefightingiotKit;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.dataaccess.dataaccess.support.utils.MyLogger;
import com.dataaccess.dataaccess.support.utils.json.JsonKeyEdit;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.*;

public class BaseService {
    @Resource
    HttpServletRequest httpServletRequest;
    HttpResponse httpResponse;
    @Resource
    public MyLogger logger;

    public List<?> toTimeStr(List<? extends Map> list, String datePattern) {
        for (Map map : list) {
            map.forEach((k, v) -> {
                if (v instanceof Timestamp) {
                    map.put(k, DateUtil.format(new Date(((Timestamp) v).getTime()), datePattern));
                }
            });
        }
        return list;
    }

    public Map<String, Object> toTimeStr(Map param, String datePattern) {
        param.forEach((k, v) -> {
            if (v instanceof Timestamp) {
                param.put(k, DateUtil.format(new Date(((Timestamp) v).getTime()), datePattern));
            }
        });
        return param;
    }

    public Map<String, Object> toTimeStr(Map param) {
        return toTimeStr(param, DatePattern.NORM_DATE_PATTERN);
    }

    public List<?> toTimeStr(List<? extends Map> list) {
        return toTimeStr(list, DatePattern.NORM_DATE_PATTERN);
    }

//    public IPage toTimeStr(IPage iPage, String datePattern) {
//        List list = iPage.getRecords();
//        iPage.setRecords(toTimeStr(list, datePattern));
//        return iPage;
//    }
//
//    public IPage toTimeStr(IPage iPage) {
//        return toTimeStr(iPage, DatePattern.NORM_DATE_PATTERN);
//    }

    //事务相关开始

    protected int batchCount = 1000;// 每批commit的个数

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 获取session
     *
     * @author <br>
     * @return session对象
     */
    public SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    }

    /**
     * 查询检测项
     * @param jsonParam
     * @return
     */
    public Map<String, String> getItme(JSONObject jsonParam){
        com.alibaba.fastjson.JSONObject item = fireFightingiotItem(jsonParam,"firefightingiot_data","getItem","alarmInfo");
        com.alibaba.fastjson.JSONArray jsonArray = item.getJSONArray("data");
        Map<String,String> map = new HashMap<>();
        if (jsonArray!=null){
            for (Object obj:jsonArray){
                com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) obj;
                map.put(jsonObject.getString("item")+";max",jsonObject.getString("max"));
                map.put(jsonObject.getString("item")+";min",jsonObject.getString("min"));
            }
            return map;
        }else {
            return map;
        }
    }
    /**
     * 获取request操作对象
     *
     * @return request操作对象
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取request操作对象
     *
     * @return request操作对象
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    /**
     * 获取session操作对象
     *
     * @return session操作对象
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

    public <A> A getMapper(SqlSession session, Class<A> type) {
        return session.getMapper(type);
    }

    public void commit(SqlSession session) {
        if (session != null) {
            session.commit();
            // 清理缓存，防止溢出
            session.clearCache();
        }
    }

    public void rollback(SqlSession session) {
        if (session != null)
            session.rollback();
    }

    public void closeSession(SqlSession session) {
        if (session != null)
            session.close();
    }
    /**
     * 大量数据批量插入
     *
     * @author <br>
     *
     */
    public class BigData {
        List<?> list = new ArrayList<>();

        public BigData(List<?> list) {
            this.list = list;
        }

        public int getNum() {
            return (int) Math.ceil(list.size() / (batchCount*1.0));
        }

        @SuppressWarnings("unchecked")
        public <TNT> TNT getData(int i) {
            return (TNT) list.subList(i * batchCount, ((i + 1) * batchCount) > list.size() ? list.size():(i + 1) * batchCount);
        }
    }

    //获取用户id
    public String getUserId(){
        return "1";
    }
    //获取部门id
    public String getDeptId(){
        return "1";
    }
    //获取机构id
    public String getOrgId(){
        return "1";
    }

    public static boolean getDatePoor(Date endDate, Date nowDate,double oper) {

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少小时
        double hour = diff / (double)nh;
        System.out.println(hour);
        if(hour>oper){
            return true;
        }
        return false;
    }


    // rest调用包装开始----------------------------------------------------------------------------------------------------------------------------

    //一企一档
    public RespEntity business(JSONObject jsonParam, String key, String gp){
        String ip = ConfigKit.getStr("business","config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            xml = HttpUtil.get(domain,jsonParam);
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonParam);
        }
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            if(jsonObject.get("data")==null){
                return RespEntity.success(jsonObject.get("data"));
            }
            else if(jsonObject.get("data") instanceof com.alibaba.fastjson.JSONObject){
                return RespEntity.success(JSONUtil.parseObj(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONObject("data").toJSONString())));
            }else{
                return RespEntity.success(JSONUtil.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString())));
            }
        }else{
            return RespEntity.success();
        }
    }
    //消防物联网(带token修改版)  gp中括号  key中括号下面
    public RespEntity fireFightingiotTwo1(JSONArray jSONArray, String configKey, String key, String gp, String tokenKey){
        String ip = ConfigKit.getStr(configKey,"config");
        String token= ConfigKit.getStr(tokenKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp)+"?"+"token="+token;
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jSONArray.toJSONString(1));
        }
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")){
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if(jsonObject.containsKey("result") && !jsonObject.getBoolean("result")){
            return RespEntity.fail(jsonObject.getString("Msg"));
        }
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            return RespEntity.success(jsonObject.get("data"));
        }else{
            return RespEntity.success(jsonObject);
        }
    }
    //消防物联网(带token修改版)  gp中括号  key中括号下面
    public RespEntity fireFightingiotTwo2(JSONArray jSONArray, String configKey, String key, String gp, String tokenKey){
        String ip = ConfigKit.getStr(configKey,"config");
        String token= ConfigKit.getStr(tokenKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp)+"?"+"token="+token;
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jSONArray.toJSONString(1));
        }
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        Object object = JSON.parse(xml);
        if(object instanceof com.alibaba.fastjson.JSONObject){
            com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)object;
            if(jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")){
                return RespEntity.fail(jsonObject.getString("Msg"));
            }
            if(jsonObject.containsKey("result") && !jsonObject.getBoolean("result")){
                return RespEntity.fail(jsonObject.getString("Msg"));
            }
        }else if(object instanceof com.alibaba.fastjson.JSONArray){
            return RespEntity.success(object);
        }
        return RespEntity.success();
    }
    //消防物联网(带token修改版)  gp中括号  key中括号下面
    public RespEntity fireFightingiotTwo(JSONObject jsonParam,String configKey,String key,String gp,String tokenKey){
        String ip = ConfigKit.getStr(configKey,"config");
        String token= ConfigKit.getStr(tokenKey,"firedocking");
        String methodPath = FirefightingiotKit.getStr(key,gp)+"?"+"token="+token;
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        if(httpServletRequest.getMethod().equalsIgnoreCase("GET")){
            xml = HttpUtil.get(domain,jsonParam);
        }else if(httpServletRequest.getMethod().equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        }
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        Object object = JSON.parse(xml);
        if(object instanceof com.alibaba.fastjson.JSONObject){
            com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject)object;
            if(jsonObject.containsKey("Success") && !jsonObject.getBoolean("Success")){
                return RespEntity.fail(jsonObject.getString("Msg"));
            }
            if(jsonObject.containsKey("result") && !jsonObject.getBoolean("result")){
                return RespEntity.fail(jsonObject.getString("Msg"));
            }
        }else if(object instanceof com.alibaba.fastjson.JSONArray){
            return RespEntity.success(object);
        }
        return RespEntity.success(object);
//        return RespEntity.success(jsonObject);
    }

    //消防物联网
    public RespEntity fireFightingiot(JSONObject jsonParam,String configKey,String key,String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        logger.info(jsonParam.toString());
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        return RespEntity.success();
    }
    //消防物联网检测项
    public com.alibaba.fastjson.JSONObject fireFightingiotItem(JSONObject jsonParam,String configKey,String key,String gp){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        return jsonObject;
    }
    /**
     * @Author YangYu
     * @Description 大华云睿专用
     * @Date Created in 16:31 2022/1/20
     * @Param [jsonObject]
     */

    public JSONObject restDHYR(JSONObject jsonParam,String configKey,String key,String gp,String token,String postOrGet){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        if("GET".equalsIgnoreCase(postOrGet)){
            httpResponse = HttpRequest.get(domain)
                    .header("Authorization",token)
                    .form(jsonParam)
                    .execute();
        }else if("POST".equalsIgnoreCase(postOrGet)){
            httpResponse = HttpRequest.post(domain)
                    .header("Authorization", "Bearer "+token)
                    .body(jsonParam.toJSONString(1))
                    .execute();
        }
        xml = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(xml);
        return jsonObject;
    }
    /**
     * @Author YangYu
     * @Description 对接安工院东营专用
     * @Date Created in 16:31 2022/1/20
     * @Param [jsonObject]
     */

    public JSONObject restDY(JSONObject jsonParam, String configKey, String key, String gp, String token, MultipartFile file) throws IOException {
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.post(domain)
                //.header("Authorization", "Bearer "+token)
                //.body(jsonParam.toJSONString(1))
                .form("alarmId",jsonParam.getStr("alarmId"))
                .form("alarmType",jsonParam.getStr("alarmType"))
                .form("alarmDate",jsonParam.getStr("alarmDate"))
                .form("alarmAction",jsonParam.getStr("alarmAction"))
                .form("deviceCode",jsonParam.getStr("alarmAction"))
                .form("channelCode",jsonParam.getStr("channelCode"))
                .form("alarmImage",file.getBytes(),file.getOriginalFilename())
                .form("areaCode",jsonParam.getStr("areaCode"))
                .form("companyName",jsonParam.getStr("companyName"))
                .form("creditCode",jsonParam.getStr("creditCode"))
                .execute();
        xml = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(xml);
        return jsonObject;
    }

    /**
     * @Author YangYu
     * @Description 对接省安工院专用
     * @Date Created in 16:31 2022/1/20
     * @Param [jsonObject]
     */

    public JSONObject restAGYAlarm(JSONObject jsonParam, String configKey, String key, String gp, String token, MultipartFile file) throws IOException {
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.post(domain)
                .form("alarmId",jsonParam.getStr("alarmId"))
                .form("alarmType",jsonParam.getStr("alarmType"))
                .form("alarmDate",jsonParam.getStr("alarmDate"))
                .form("alarmAction",jsonParam.getStr("alarmAction"))
                .form("deviceCode",jsonParam.getStr("deviceCode"))
                .form("channelCode",jsonParam.getStr("channelCode"))
                .form("alarmImage",file.getBytes(),file.getOriginalFilename())
                .execute();
        xml = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(xml);
        return jsonObject;
    }
    /**
     * @Author YangYu
     * @Description 对接省安工院专用
     * @Date Created in 16:31 2022/1/20
     * @Param [jsonObject]
     */

    public JSONObject restAGYStopAlarm(JSONObject jsonParam, String configKey, String key, String gp, String token, MultipartFile file) throws IOException {
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.post(domain)
                .form("alarmId",jsonParam.getStr("alarmId"))
                .form("alarmType",jsonParam.getStr("alarmType"))
                .form("alarmDate",jsonParam.getStr("alarmDate"))
                .form("alarmAction",jsonParam.getStr("alarmAction"))
                .form("deviceCode",jsonParam.getStr("deviceCode"))
                .form("channelCode",jsonParam.getStr("channelCode"))
                .form("alarmImage",file.getBytes(),file.getOriginalFilename())
                .form("areaCode",jsonParam.getStr("areaCode"))
                .form("companyName",jsonParam.getStr("companyName"))
                .form("creditCode",jsonParam.getStr("creditCode"))
                .execute();
        xml = httpResponse.body();
        JSONObject jsonObject = JSONUtil.parseObj(xml);
        return jsonObject;
    }
    //消防物联网
    public RespEntity restPostOrGet(JSONObject jsonParam,String configKey,String key,String gp,String postOrGet){
        String ip = ConfigKit.getStr(configKey,"config");
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        logger.info("------------------------------domain:" + domain + "-----------------------------------------");
        String xml = "";
        if(postOrGet.equalsIgnoreCase("GET")){
            xml = HttpUtil.get(domain,jsonParam);
        }else if(postOrGet.equalsIgnoreCase("POST")){
            xml = HttpUtil.post(domain,jsonParam.toJSONString(1));
        }
        logger.info("------------------------------xml:" + xml + "-----------------------------------------");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            return RespEntity.fail(jsonObject.getString("msg"));
        }
        if(postOrGet.equalsIgnoreCase("GET")){
            return RespEntity.success(jsonObject.get("data"));
        }else{
            return RespEntity.success();
        }
    }

    public static JSONObject sendPostUrlTwo(String url, String param) throws  Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        JSONObject jsonObject = null;
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        URLConnection conn = realUrl.openConnection();
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);

        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json");
        // 获取URLConnection对象对应的输出流（设置请求编码为UTF-8）
        out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        System.err.println(out);
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 获取请求返回数据（设置返回数据编码为UTF-8）
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        System.err.println(result);//打印返回结果   
        return jsonObject;
    }

    //组装数据
    public com.alibaba.fastjson.JSONObject makeData(JSONObject jsonParam,String configKey,String configPg,String key,String gp){
        String ip = ConfigKit.getStr(configKey,configPg);
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = "";
        httpResponse = HttpRequest.get(domain)
                .header("Authorization", httpServletRequest.getHeader("Authorization"))
                .form(jsonParam)
                .execute();
        xml = httpResponse.body();
        int state = httpResponse.getStatus();
        if(state == 401) return RespEntity.expire();
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg",jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag","1");
            return errorObject;
        }
        if(configKey.equals("business") || configKey.equals("check")){
            com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONObject("data").toJSONString()));
            return data;
        }

        return jsonObject.getJSONObject("data");
    }
    //组装数据:处理返回即可能是JSONObject又可能是JsonArray的情况
    public JSON makeDataForJSON(JSONObject jsonParam,String configKey,String configPg,String key,String gp){
        String ip = ConfigKit.getStr(configKey,configPg);
        String methodPath = FirefightingiotKit.getStr(key,gp);
        String domain = ip + methodPath;
        String xml = HttpUtil.get(domain,jsonParam);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(xml);
        if(jsonObject.getInteger("code")==1){
            com.alibaba.fastjson.JSONObject errorObject = new com.alibaba.fastjson.JSONObject();
            errorObject.put("msg",jsonObject.getString("msg"));
            errorObject.put("methodErrorFlag","1");
            return errorObject;
        }
        if(configKey.equals("business") || configKey.equals("check")){
            com.alibaba.fastjson.JSONArray data = com.alibaba.fastjson.JSONArray.parseArray(JsonKeyEdit.jsonKeyEdit(jsonObject.getJSONArray("data").toJSONString()));
            return data;
        }
        return jsonObject.getJSONArray("data");
    }

// rest调用包装结束----------------------------------------------------------------------------------------------------------------------------

}
